package com.hm.ibsm.service;

import java.util.List;

import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hm.common.network.httpclient.HttpClientFactory;
import com.hm.common.network.httpclient.HttpClientResponseParse;
import com.hm.common.su.ServerResponseParse;
import com.hm.common.su.bean.ServerResponse;
import com.hm.ibsm.manage.vo.auth.AuthUserVo;
import com.hm.ibsm.manage.vo.auth.UserMenuVo;
import com.hm.ibsm.util.LocationConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 2017年3月6日 下午11:14:07
 * @version 1.0
 * @describe
 */
@Slf4j
@Component
public class AuthService {

	@Autowired
	private LocationConfig locationConfig;

	protected static String LOAD_USER_MENUS = "/auth/user/menus";

	protected static String LOGIN_URI = "/auth?account={0}&pwd={1}";

	protected static String MODEL_NAME = AuthService.class.getName();

	public AuthUserVo login(String account, String pwd) throws Exception {
		HttpResponse response = HttpClientFactory.POST.build(locationConfig.mgUri(LOGIN_URI), account, pwd).execute();
		AuthUserVo authUser = ServerResponseParse.parse(HttpClientResponseParse.parseGeneric(response, new TypeReference<ServerResponse<AuthUserVo>>() {
		}));
		return authUser;
	}

	public JSONArray loadUserMenu() {
		try {
			HttpResponse response = locationConfig.accredit(HttpClientFactory.PATCH.build(locationConfig.mgUri(LOAD_USER_MENUS))).execute();
			List<UserMenuVo> menus = ServerResponseParse
					.parse(HttpClientResponseParse.parseGeneric(response, new TypeReference<ServerResponse<List<UserMenuVo>>>() {
					}));

			return loopMenus(menus, new JSONArray(), "0",true);
		} catch (Exception e) {
			log.error(MODEL_NAME, e);
		}
		return new JSONArray();
	}

	private JSONArray loopMenus(List<UserMenuVo> menus, JSONArray items, String parentId,boolean spread) {
		for (UserMenuVo menu : menus) {
			JSONObject item = new JSONObject();
			{
				item.put("icon", menu.getIcon());
				item.put("title", menu.getMenuName());
				item.put("href", menu.getUri());
				if(spread){
					item.put("spread", spread);
				}
			}
			if (menu.isHasChild()) {
				item.put("children", loopMenus(menu.getChilds(), new JSONArray(), menu.getMenuId(),false));
			}
			items.add(item);
		}
		return items;
	}
}
